package wechat.rcv;

import java.util.Date;
import java.util.Random;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import wechat.rcv.cosuming.EventClickConsuming;
import wechat.rcv.cosuming.IMsgConsuming;
import wechat.rcv.cosuming.RequestObj;
import wechat.rcv.cosuming.TxtMsgConsuming;
import wechat.rcv.cosuming.WXRequestTree;
import wechat.rcv.util.RequestParser;
import weixin.mp.aes.AesException;

@RestController
@RequestMapping("/corpapp")
@ResponseBody
public class FrontController {
	
	@Autowired
	WXRequestTree wxRequestTree;
	
	final static Logger logger = Logger.getLogger(FrontController.class.getName());
	@RequestMapping(method = RequestMethod.GET)
	public String CorpUrlValidation(@RequestParam(value = "msg_signature", defaultValue = "") String msg_signature,
			@RequestParam(value = "timestamp", defaultValue = "") String timestamp,
			@RequestParam(value = "nonce", defaultValue = "") String nonce,
			@RequestParam(value = "echostr", defaultValue = "") String echostr) {
		logger.info("***WeXinCorpApplication GET Request received!***");
		logger.info("msg_signature = "+ msg_signature);
		logger.info("timestamp = "+ timestamp);
		logger.info("nonce = "+ nonce);
		logger.info("echostr = "+ echostr);

		String sEchoStr = "";
		try {
			sEchoStr = RcvToken.getWxcpt().VerifyURL(msg_signature, timestamp, nonce, echostr);
		} catch (AesException e) {
			// TODO Auto-wechat.rcv.generated catch block
			e.printStackTrace();
		}
		return sEchoStr;
	}
<<<<<<< HEAD
//	@RequestMapping(value="/serviceapp", method = RequestMethod.GET)
=======
//	@RequestMapping( method = RequestMethod.GET)
>>>>>>> c0718edfebc821177ce7d74566d85a4d72d51c63
//	public String ServiceAppUrlValidation(@RequestParam(value = "msg_signature", defaultValue = "") String msg_signature,
//			@RequestParam(value = "timestamp", defaultValue = "") String timestamp,
//			@RequestParam(value = "nonce", defaultValue = "") String nonce,
//			@RequestParam(value = "echostr", defaultValue = "") String echostr) {
//		logger.info("***GET Request received!***");
//		logger.info("msg_signature = "+ msg_signature);
//		logger.info("timestamp = "+ timestamp);
//		logger.info("nonce = "+ nonce);
//		logger.info("echostr = "+ echostr);
//
//		String sEchoStr = "";
//		try {
//			sEchoStr = RcvToken.getServiceAppWxcpt().VerifyURL(msg_signature, timestamp, nonce, echostr);
//		} catch (AesException e) {
//			// TODO Auto-wechat.rcv.generated catch block
//			e.printStackTrace();
//		}
//		return sEchoStr;
//	}
	
	//CorpApp Event Entry Controller
	@RequestMapping(value="/serviceapp", method = RequestMethod.POST, headers = {
			"Accept=application/xml;charset=UTF-8" }, produces = MediaType.APPLICATION_XML_VALUE)
	public String CallbackRequest(@RequestParam(value = "msg_signature", defaultValue = "") String msg_signature,
			@RequestParam(value = "timestamp", defaultValue = "") String timestamp,
			@RequestParam(value = "nonce", defaultValue = "") String nonce, @RequestBody String input
	// ,HttpServletResponse response
	) {
		logger.info("************POST Request received!************");
		try {
			String sMsg = RcvToken.getWxcpt().DecryptMsg(msg_signature, timestamp, nonce, input);
			logger.info("Decypted message is " + sMsg);
			
			RequestObj req = new RequestObj(sMsg);
//			
			// Response
//			String replyMsg = getHandleObject(sMsg).acceptSync();
			String replyMsg = wxRequestTree.getHandler(req).acceptSync();
			logger.info("reply message ---" + replyMsg);
			return generateResponse(replyMsg);
		} catch (AesException e) {
			e.printStackTrace();
			logger.error("Decypte message error!--" + " code: " + e.getCode());
		} catch (Exception e) {
			// TODO Auto-wechat.rcv.generated catch block
			e.printStackTrace();
			logger.error("getHandleObject return null");
		}
		return "";
	}

//	private IMsgConsuming getHandleObject(String xmlmsg) throws Exception{
//		IMsgConsuming ret = null;
//		String msgType = RequestParser.getMsgType(xmlmsg);
//		if (msgType.equalsIgnoreCase("text")) {
//			ret = new TxtMsgConsuming(xmlmsg);
//		} else if (msgType.equalsIgnoreCase("event")) {
//			if (RequestParser.getElementByTag(xmlmsg, "Event").equalsIgnoreCase("click"))
//				ret = new EventClickConsuming(xmlmsg);
//		}
//		if (ret==null){
//			logger.info("msgType is " + msgType);
//			throw new Exception();
//		}
//		return ret;
//	}

	private int getRandom() {
		int max = 99999999;
		int min = 10;
		Random random = new Random();
		return random.nextInt(max) % (max - min + 1) + min;
	}

	private String generateResponse(String replyMsg) {

		String timestamp = Long.toString(new Date().getTime());
		String nonce = Long.toString(getRandom());
		try {
			return RcvToken.getWxcpt().EncryptMsg(replyMsg, timestamp, nonce);
		} catch (AesException e) {
			// TODO Auto-wechat.rcv.generated catch block
			e.printStackTrace();
			return "";
		}
	}
}
